﻿////#define DEBUG_SCHEDULE

namespace USElections.TileUpdates
{
    using System.Diagnostics;
    using System.Threading.Tasks;
    using AgFx;
    using Microsoft.Phone.Scheduler;
    using USElections.Model;

    /// <summary>
    /// ScheduledAgent class.
    /// </summary>
    public class ScheduledAgent : ScheduledTaskAgent
    {
        /// <summary>
        /// Invokes the Background task.
        /// </summary>
        /// <param name="task">The task to invoke.</param>
        protected override void OnInvoke(ScheduledTask task)
        {
            Debug.WriteLine("Starting BackgroundTask");

            int previousVoteCount = NorthernLights.PersistentVariables.Get<int>(Model.Enums.Variables.PreviousVoteCount.ToString());

            VotesModel vm = this.GetLatestVotesModel().Result;

            if (vm != null)
            {
                int totalCount = vm.TotalVoteCount;

                if (previousVoteCount <= totalCount)
                {
                    ApplicationTile.Update(totalCount - previousVoteCount);
                }
            }

            // If debugging is enabled, launch the agent again in one minute.
#if DEBUG_SCHEDULE
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif

            Debug.WriteLine("Ending BackgroundTask"); 
            
            NotifyComplete();
        }

        private Task<VotesModel> GetLatestVotesModel()
        {
            TaskCompletionSource<VotesModel> tcs = new TaskCompletionSource<VotesModel>();

            DataManager.Current.Refresh<VotesModel>(
                "votes",
                (vm) =>
                {
                    tcs.TrySetResult(vm);
                },
                (vm) =>
                {
                    tcs.TrySetResult(null);
                });

            Task.WaitAny(tcs.Task);

            return tcs.Task;
        }
    }
}
